package beautiful.butterfly.drds.binlog.handlers;


import beautiful.butterfly.drds.binlog.command.AuthenticateCommand;
import beautiful.butterfly.drds.binlog.utils.ByteUtils;
import beautiful.butterfly.drds.binlog.utils.Nettys;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class GreetingPacketResultChannelInboundHandler extends SimpleChannelInboundHandler<ByteBuf>
{


    @SuppressWarnings("unused")
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception
    {
        //
        try
        {
            // 在这里处理收到的消息
            // LoggerUtils.debug(logger, "enter GreetingPacketHandler -
            // channelRead0 (...)");
            // LoggerUtils.debug(logger, "msg length:" + msg.readableBytes());
            // 收到了一个完整的Greeting Packet...
            if (null == byteBuf)
            {
                return;
            }
            // 1第1个字节是版本号
            int protocolVersion = ByteUtils.readUnsignedByte(byteBuf);// 一个字节
            // if ((byte) 0xFF == (byte) protocolVersion) {
            // LoggerUtils.error(logger, "wrong protocol version");
            // 出错必须关闭
            // }
            log.info("mysql protocol version: " + protocolVersion);
            // LoggerUtils.debug(logger, "" + msg);

            // 2 第2部分是serverVersion,一个以\0结束的字符串
            String serverVersion = ByteUtils.readZeroTerminatedString(byteBuf);
            log.info("serverVersion:" + serverVersion);
            // LoggerUtils.debug(logger, "" + msg);

            // 3 接下来四个字节是threadId
            long threadId = ByteUtils.readUnsignedLong(byteBuf, 4);
            log.info("threadId: " + threadId);

            // 4第4部分是scramblePrefix,一个以\0结束的字符串
            String scramblePrefix = ByteUtils.readZeroTerminatedString(byteBuf);
            // LoggerUtils.debug(logger, "scramblePrefix-" + scramblePrefix);

            // 5 接下来取2个字节
            int serverCapabilities = ByteUtils.readUnsignedInt(byteBuf, 2);
            // LoggerUtils.debug(logger, "serverCapabilities-" +
            // serverCapabilities);
            // 6接下来取1个字节
            int serverCollation = ByteUtils.readUnsignedByte(byteBuf);
            // LoggerUtils.debug(logger, "serverCollation: " + serverCollation);
            // 7 接下来2个字节为serverStatus
            int serverStatus = ByteUtils.readUnsignedInt(byteBuf, 2);
            // LoggerUtils.debug(logger, "serverStatus: " + serverStatus);
            // 8 接下来保留13个字节
            byteBuf.skipBytes(13);

            // 9接下来是一个以\0结尾的字符串
            String scrambleSuffix = ByteUtils.readZeroTerminatedString(byteBuf);
            String scramble = scramblePrefix + scrambleSuffix;
            // LoggerUtils.debug(logger, "scramble: " + scramble);
            // 可能还有其它的内容，暂时忽略,节省开销
            // String others = ByteUtils.readZeroTerminatedString(msg);
            // 发送验证命令
            new AuthenticateCommand(scramble, serverCollation).write(channelHandlerContext);
            channelHandlerContext.pipeline().remove(this);// 完成使命，退出历史舞台
        } catch (Exception e)
        {
            log.info(e.toString());
            throw new Exception(e);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable throwable)
    {
        // Close the connection when an exception is raised.
        // cause.printStackTrace();//务必要关闭
        log.info(throwable.toString());
        Nettys.cleanChannelContext(channelHandlerContext, throwable);
    }

    @Override
    public void channelInactive(ChannelHandlerContext channelHandlerContext) throws Exception
    {
        log.info("[channelInactive] socket is closed by remote server");
        Nettys.cleanChannelContext(channelHandlerContext, null);
    }

}
